package 数据结构和算法.剑指offer.字符串.替换空格;

import 工具.打印.PrintUtil;

/**
 * 辅助字符数组：如果当前字符串的指针位置不是空格则将该字符加入新字符串，
 * 否则将%20三个字符加入新的字符串
 * <p>
 * StringBuilder：使用StringBuilder中的方法
 */
public class Test {
    public static void main(String[] args) {
        String s = "a d f";
        PrintUtil.println(replaceSpaceOne(s));
        PrintUtil.println(replaceSpaceTwo(s));
    }

    public static String replaceSpaceOne(String s) {
        char[] array = new char[s.length() * 3];
        int size = 0;
        for (int i = 0; i < s.length(); ++i) {
            char temp = s.charAt(i);
            if (temp == ' ') {
                array[size++] = '%';
                array[size++] = '2';
                array[size++] = '0';
            } else {
                array[size++] = temp;
            }
        }

        String result = new String(array, 0, size);
        return result;
    }

    public static String replaceSpaceTwo(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        char[] array = s.toCharArray();
        for (char c : array) {
            if (c == ' ') {
                stringBuilder.append("%20");
            } else {
                stringBuilder.append(c);
            }
        }

        return stringBuilder.toString();
    }
}
